/**
 * sdk管理器
 */

import ksBannerManager from "./ks/ksBannerManager";
import { ksBuriedPoint } from "./ks/ksBuriedPoint";
import ksInterstitialManager from "./ks/ksInterstitialManager";
import ksRewardVideoManager from "./ks/ksRewardVideoManager";
import wxInterstitialManager from "./wx/wxInterstitialManager";
import wxRewardVideoManager from "./wx/wxRewardVideoManager";
import BaseManager from "./zijie/BaseManager";
import { BuriedPoint } from "./zijie/BuriedPoint";
import InterstitialManager from "./zijie/InterstitialManager";
import RewardVideoManager from "./zijie/RewardVideoManager";
import zijieConfig from "./zijieConfig";

//平台枚举
export enum Platform {
    ks="ks",
    wx="wx",
    oppo="oppo",
    vivo="vivo",
    zijie="tt",
}

export default class SDKManager {

    public static _s_instance: SDKManager | null = null;
    public static getInstance(): SDKManager {
        if (!this._s_instance) {
            this._s_instance = new SDKManager();

        }
        return this._s_instance;
    }

    static isAd: boolean = false;
    private START_TIME_KEY: string = 'app_start_time';

    platform: string = Platform.zijie

    //---------------------------------------------------Banner---------------------------------------------
    public _isBannerVisible = false;
    public _isBannerScuuess = false;
    private _bannerHeight = 0;
    /**
     * 显示Banner
     */
    public showBanner() {
        this._isBannerVisible = true;

        switch (this.platform) {
            case Platform.oppo:
                break;
            case Platform.vivo:
                break;
            case Platform.ks:
                ksBannerManager.getInstance().showBannerAD();
                break;
            default:
                break;
        }

    }
    /**
     * 隐藏Banner
     */
    public hideBanner() {
        this._isBannerVisible = false;


        switch (this.platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            case Platform.ks:
                ksBannerManager.getInstance().hideBannerAd();
                break;
            default:
                break;
        }

    }


    /**
     * Banner数据请求成功
     */
    public static onBannerSuccess() {
        SDKManager.getInstance()._isBannerScuuess = true;
    }

    showInterstitial(){

        switch (this.platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            case Platform.ks:
                ksInterstitialManager.getInstance().showInterstitialAd();
                break;
            case Platform.zijie:
                InterstitialManager.getInstance().showInterstitialAd();
                break;
            case Platform.wx:
                wxInterstitialManager.getInstance().showInterstitialAd();
                break;
            default:
                break;
        }

    }


    /**
     * 展示插原生模版
     */
    public showCustom() {
        switch (this.platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            default:
                break;
        }


    }
    public hideCustom() {
        switch (this.platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            default:
                break;
        }

    }





    //---------------------------------------------------激励---------------------------------------------

    reward_node=null;
    reward_index:number=0;
    /**
     * 展示激励
     * @param pNode 点击的node
     * @param callbackTarget 回调的node
     * @param callback 回调的方法
     */
    public showRewardVideos(pNode:  cc.Node, callbackTarget: any = null, callback: Function = function () { }, callback2: Function = function () { }) {

        switch (this.platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            case Platform.ks:
                ksRewardVideoManager.getInstance().rewardVideoSuccess = false;
                ksRewardVideoManager.getInstance().onClickLock(pNode, callbackTarget, callback, callback2)
                break;
            case Platform.zijie:
                RewardVideoManager.getInstance().rewardVideoSuccess = false;
                RewardVideoManager.getInstance().onClickLock(pNode, callbackTarget, callback, callback2)
                break;
            case Platform.wx:
                wxRewardVideoManager.getInstance().rewardVideoSuccess = false;
                wxRewardVideoManager.getInstance().onClickLock(pNode, callbackTarget, callback, callback2)
                break;
            default:
                callback();
                break;
        }

    }


    public addRewardVideos() {

        switch (this.platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            case Platform.ks:
                ksRewardVideoManager.getInstance().addRewardVideoAd();
                break;
            case Platform.zijie:
                RewardVideoManager.getInstance().addRewardVideoAd();
                break;
            case Platform.wx:
                wxRewardVideoManager.getInstance().addRewardVideoAd();
                break;
            default:

                break;
        }

    }
    /**
     * 激励结束, 观看结束，发放奖励
     * 激励结束, 没观看结束，取消
     */
    public static onRewardVideoClose() {


        switch (SDKManager.getInstance().platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            case Platform.ks:
                ksRewardVideoManager.getInstance().onRewardVideoClose(false);
                break;
            case Platform.zijie:
                RewardVideoManager.getInstance().onRewardVideoClose(false);
                break;
            case Platform.wx:
                wxRewardVideoManager.getInstance().onRewardVideoClose(false);
                break;
            default:

                break;
        }

    }
    public static onRewardVideoCloseComplete() {


        switch (SDKManager.getInstance().platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            case Platform.ks:
                ksRewardVideoManager.getInstance().onRewardVideoClose(true);
                break;
            case Platform.zijie:
                RewardVideoManager.getInstance().onRewardVideoClose(true);
                break;
            case Platform.wx:
                wxRewardVideoManager.getInstance().onRewardVideoClose(true);
                break;
            default:

                break;
        }
    }
    /**
     * 激励数据请求成功
     */
    public static onRewardVideoSuccess() {


        switch (SDKManager.getInstance().platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            case Platform.ks:
                ksRewardVideoManager.getInstance().rewardVideoSuccess = true;
                break;
            case Platform.zijie:
                RewardVideoManager.getInstance().rewardVideoSuccess = true;
                break;
            case Platform.wx:
                wxRewardVideoManager.getInstance().rewardVideoSuccess = true;
                break;
            default:

                break;
        }
    }

    /**
     * 更多游戏
     */
    public onMore() {
        switch (this.platform) {
            case Platform.zijie:
                BaseManager.getInstance().onMoreGames();
                break;
            case Platform.vivo:

                break;
            case Platform.oppo:

                break;
            default:
                break;
        }

    }
    /**
     * 游戏Banner
     */
    public showGameBanner() {
        switch (this.platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            default:
                break;
        }

    }
    /**
     * 游戏Banner
     */
    public closeGameBanner() {
        switch (this.platform) {
            case Platform.zijie:

                break;
            case Platform.vivo:

                break;
            default:
                break;
        }

    }


    isfirst: boolean = false;
    /**
     * 广告初始化
     */
    public onInit() {
        if (this.isfirst)
            return;
        this.isfirst = true;


        switch (this.platform) {
            case Platform.oppo:

                break;
            case Platform.vivo:

                break;
            case Platform.ks:
                this.get_ks_openId();

                ksBannerManager.getInstance();
                // ksInterstitialManager.getInstance();
                // ksRewardVideoManager.getInstance();


                break;
            case Platform.zijie:
                InterstitialManager.getInstance();

                RewardVideoManager.getInstance();

                BaseManager.getInstance().initNavigate();

                this.whenStartClick();
                this.Getopenid();
                break;
            case Platform.wx:
                wxInterstitialManager.getInstance();

                wxRewardVideoManager.getInstance();
                break;
            default:

                break;
        }
    }

    openid:string="";

    Getopenid() {
        tt.login({
            success(res) {
                if (res.code) {
                    tt.getUserInfo({
                        success(ress) {
                            try {
                                // 同步获取系统信息
                                var resInfo = tt.getSystemInfoSync();

                                // 输出所有系统信息字段
                                console.log(`操作系统版本 (system): ${resInfo.system}`);
                                console.log(`操作系统类型 (platform): ${resInfo.platform}`);
                                console.log(`手机品牌 (brand): ${resInfo.brand}`);
                                console.log(`手机型号 (model): ${resInfo.model}`);
                                console.log(`宿主 App 版本号 (version): ${resInfo.version}`);
                                console.log(`宿主 App 名称 (appName): ${resInfo.appName}`);
                            } catch (error) {
                                // 捕获异常并输出错误信息
                                console.log(`获取系统信息失败: ${error.message}`);
                            }
                            tt.request({
                                url: 'https://ecpm.shumumedia.com/api/public/user', // 接口地址
                                method: 'POST', // 请求方法
                                data: {
                                    avatarUrl:ress.userInfo.avatarUrl, // 用户信息（假设已定义）
                                    nickName:ress.userInfo.nickName,
                                    code: res.code, // 登录凭证（假设已定义）
                                    appId: 'ttdb54ade9445bd1ba02', // 小程序 APPID（必填）
                                    // 添加系统信息字段
                                    system: resInfo.system, // 操作系统版本
                                    platform: resInfo.platform, // 操作系统类型
                                    brand: resInfo.brand, // 手机品牌
                                    model: resInfo.model, // 手机型号
                                    version: resInfo.version, // 宿主 App 版本号
                                    appName: resInfo.appName, // 宿主 App 名称
                                },
                                success(response) {
                                    console.log('抖音 OpenID:', response.data.data.openId,response.data.data.userId);
                                    SDKManager.getInstance().openid = response.data.data.userId;
                                },
                                fail(error) {
                                    console.error('请求失败:', error);
                                }
                            });

                        },
                        fail(err) {
                            console.log(err);

                        },
                    });

                }
            }
        });


    }
    ks_openid:string="";
    get_ks_openId(){
        let ks = window["ks"] || undefined;
        if (ks == null)
            return;
        // 获取临时登录凭证 code
        let self=this;
        ks.login({
            success: function (res) {
                if (res.code) {
                    let code = res.code;
                    // 在这里可以将 code 发送到服务器进行换取 openid 请求
                    console.log('获取到的 code:', code);
                    self.getKsOpenId(res.code);
                } else {
                    console.log('登录失败！' + res.errMsg);
                }
            },
            fail: function (err) {
                console.log('ks.login 失败:', err);
            }
        })
    }

    async getKsOpenId(_code) {
        // try {
        //     const response = await fetch(`https://ksopenid.qibaimeng.com/api.php?app_id=${zijieConfig.ks_appId}&app_secret=${zijieConfig.ks_secret}&code=${_code}`, {
        //         method: 'GET',
        //         headers: {
        //             'Content-Type': 'application/json',
        //         },
        //         body: JSON.stringify({
        //             app_id: zijieConfig.ks_appId,
        //             app_secret: zijieConfig.ks_secret,
        //             code: _code // 从小游戏前端获取的code
        //         })
        //     });

        //     const data = await response.json();

        //     if (data.success) {
        //         console.log('OpenID获取成功:', data.data.open_id);
        //         // 处理获取到的open_id
        //         this.ks_openid=data.data.open_id;
        //     } else {
        //         console.error('获取失败:', data.message);
        //     }
        // } catch (error) {
        //     console.error('请求出错:', error);
        // }

        // 发起 GET 请求
        const url = "https://ksopenid.qibaimeng.com/api.php?app_id=" + zijieConfig.ks_appId + "&app_secret=" + zijieConfig.ks_secret + "&code=" + _code;
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    try {
                        // 解析 JSON 响应
                        const response = JSON.parse(xhr.responseText);
                        if (response.success && response.data.open_id) {
                            const openId = response.data.open_id;
                            console.log("获取到 open_id:", openId);
                            // 可选：更新 UI 显示

                            this.ks_openid = openId;
                        } else {
                            console.error("响应格式错误，未找到 open_id");
                        }
                    } catch (error) {
                        console.error("JSON 解析失败:", error);
                    }
                } else {
                    console.error("请求失败，状态码:", xhr.status);
                }
            }
        }.bind(this); // 绑定 this 上下文

        xhr.send();
    }


    isclick:boolean=false;
    ShareEvent() {
        if(window["wx"]){
            this.tt = window["wx"] || undefined;
            if (this.tt == null)
                return;
            if (this.isclick == false) {
                this.isclick = true;

                setTimeout(() => {
                    this.isclick = false
                }, 200);
                this.tt.shareAppMessage({
                    channel: "",
                    //title: "分享视频",
                    desc: "",
                    templateId: "", // 替换成通过审核的分享ID
                    query: "",
                    success() {
                        console.log("分享成功");
                    },
                    fail(e) {
                        console.log("分享失败");
                    },
                });
            }
        }else if(window["tt"]){
            this.tt = window["tt"] || undefined;
            if (this.tt == null)
                return;
            if (this.isclick == false) {
                this.isclick = true;

                setTimeout(() => {
                    this.isclick = false
                }, 200);
                this.tt.shareAppMessage({
                    channel: "",
                    //title: "分享视频",
                    desc: "",
                    templateId: "", // 替换成通过审核的分享ID
                    query: "",
                    success() {
                        console.log("分享成功");
                    },
                    fail(e) {
                        console.log("分享失败");
                    },
                });
            }
        }


    }

    tt:any=null;
    //激活
    whenStartClick() {
        if(window["ks"]){
            return;
        }
        if(window["wx"]){
            this.tt = window["wx"] || undefined;
        }else if(window["tt"]){
            this.tt = window["tt"] || undefined;
        }

        if (this.tt == null)
            return;
        var launch = this.tt.getLaunchOptionsSync();
        console.log("调用激活方法")
        console.log(launch.query.clickid)

        if (typeof launch.query.clickid != "undefined") {

            const timestampInSeconds = Math.floor(new Date().getTime() / 1000);

            this.tt.request({
                url: "https://analytics.oceanengine.com/api/v2/conversion",
                data: {
                    "event_type": "active",
                    "context": {
                        "ad": {
                            "callback": launch.query.clickid,
                        },
                    },
                    "timestamp": timestampInSeconds
                },
                header: {
                    "content-type": "application/json",
                },
                method: "POST",
                dataType: "JSON", // 指定返回数据的类型为 json
                responseType: "text",
                success(res) {
                    console.warn("调用成功", res.data);
                },
                fail(res) {
                    console.warn("调用失败", res.errMsg);
                },
            });

        }
    }

    //埋点
    whenAdClick() {
        if(window["ks"]){
            return;
        }
        if(window["wx"]){
            this.tt = window["wx"] || undefined;
        }else if(window["tt"]){
            this.tt = window["tt"] || undefined;
        }
        if (this.tt == undefined)
            return;
        var launch = this.tt.getLaunchOptionsSync();
        console.log("调用埋点方法")
        console.log(launch.query.clickid)

        if (typeof launch.query.clickid != "undefined") {

            const timestampInSeconds = Math.floor(new Date().getTime() / 1000);

            this.tt.request({
                url: "https://analytics.oceanengine.com/api/v2/conversion",
                data: {
                    "event_type": "game_addiction",
                    "context": {
                        "ad": {
                            "callback": launch.query.clickid,
                        },
                    },
                    "timestamp": timestampInSeconds
                },
                header: {
                    "content-type": "application/json",
                },
                method: "POST",
                dataType: "JSON", // 指定返回数据的类型为 json
                responseType: "text",
                success(res) {
                    console.warn("调用成功", res.data);
                },
                fail(res) {
                    console.warn("调用失败", res.errMsg);
                },
            });

        }
    }

    checkAd() {
        // 检查是否是第一次启动
        let startTime = localStorage.getItem(this.START_TIME_KEY);
        if (!startTime) {
            // 如果是第一次启动，记录当前时间
            const currentTime = new Date().getTime();
            localStorage.setItem(this.START_TIME_KEY, currentTime.toString());
        } else {
            // 如果不是第一次启动，计算时间间隔
            const storedTime = parseInt(startTime);
            const currentTime = new Date().getTime();
            const timeDiff = currentTime - storedTime;
            const daysDiff = timeDiff / (1000 * 60 * 60 * 24);

            // 如果时间间隔超过 3 天，将开关设置为 true
            if (daysDiff >= 3) {
                SDKManager.isAd = true;
            }
        }

        // 打印开关状态
        console.log('isAd:', SDKManager.isAd);
    }
}

window["SDKManager"] = SDKManager.getInstance();